#include <iostream>
#include <map>
#include <queue>
#include <vector>
using namespace std;
class Solution
{
public:
    struct Compare
    {
        bool operator()(const pair<string, int> &x, const pair<string, int> &y) const
        {
            return (x.second < y.second) || (x.second == y.second && x.first > y.first);
        }
    };
    vector<string> topKFrequent(vector<string> &words, int k)
    {
        map<string, int> mapcount;
        for (auto &e : words)
        {
            mapcount[e]++;
        }
        priority_queue<pair<string, int>, vector<pair<string, int>>, Compare> pq(mapcount.begin(), mapcount.end());
        vector<string> v;
        while (k--)
        {
            v.push_back(pq.top().first);
            pq.pop();
        }
        return v;
    }
};